package com.education.welco.controller.app;


import com.education.common.core.BaseController;
import com.education.common.pojo.AjaxResult;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.StringUtils;
import com.education.utils.BaiduAipContentCensor;
import com.education.websocket.data.HomeBuffer;
import com.education.websocket.data.HomeData;
import com.education.websocket.server.WebSocketServerWELCO;
import com.education.welco.feign.userFeign;
import com.education.welco.pojo.*;
import com.education.welco.service.*;
import com.education.welco.service.impl.TTeacherServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 教师答疑 信息操作处理
 *
 * @author d
 * @date 2020-05-08
 */
@Api(tags = {"APP-学校课程--答疑"})
@RestController
@RequestMapping("/app/sAnswering")
public class AppSAnsweringController extends BaseController {

    @Autowired
    private BaiduAipContentCensor baiduAipContentCensor;
    @Autowired
    private ISReportService reportService;
    @Autowired
    private ISAnsweringLikeService answeringLikeService;
    @Autowired
    private ISAnsweringCommentService sAnsweringCommentService;
    @Autowired
    private ISAnsweringService answeringService;
    @Autowired
    private ISCatalogService isCatalogService;
    @Autowired
    private ISAnswerUserService isAnswerUserService;
    @Autowired
    private userFeign userFeign;
    @Autowired
    private ISCatalogMenuService catalogMenuService;
    @Autowired
    private TTeacherServiceImpl tTeacherService;
    @Autowired
    private IMessageNotificationService messageNotificationService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private HomeBuffer homeBuffer;

    /**
     * 查找答疑详情  (答疑主题、老师名称、创建时间、) (评论)
     *
     * @param answerId 答疑主键id
     * @return
     */
    @GetMapping("/detail")
    @ApiOperation(value = "查找答疑详情", httpMethod = "GET")
    public AjaxResult sAnsweringdetail(@RequestParam(value = "answerId", required = true) Integer answerId) {
        //1.查答疑的数据  (答疑主题、老师名称、创建时间、)   关联老师表
        SAnswering sAnswering = answeringService.selectSAnsweringById(answerId);
        return AjaxResult.success(sAnswering);
    }

    /**
     * 查找答疑详情评论   (评论)    最新OR热门
     *
     * @param answerId 答疑主键id
     * @param userId   当前用户id
     * @param type     最热or最新- 1为最新2为最热
     * @return
     */
    @GetMapping("/detailComment")
    @ApiOperation(value = "查找答疑详情评论", httpMethod = "GET")
    public AjaxResult sAnsweringDetailComment(@RequestParam(value = "answerId", required = true) String answerId,
                                              @RequestParam(value = "userId", required = true) String userId,
                                              @RequestParam(value = "type", required = true) String type) {

        return sAnsweringCommentService.selectCommentListById(answerId, userId, type);
    }


    /**
     * @param resId  评论的父级id
     * @param userId 评论人id
     * @param text   评论内容
     * @param level  评论层级
     * @return
     */
    @GetMapping("/commentAdd")
    @ApiOperation(value = "答疑详情评论新增", httpMethod = "GET")
    public AjaxResult sAnsweringDetailcommentAdd(@RequestParam(value = "resId", required = true) String resId,
                                                 @RequestParam(value = "userId", required = true) String userId,
                                                 @RequestParam(value = "text", required = true) String text,
                                                 @RequestParam(value = "level", required = true) String level) {
        //String wordStr = String.valueOf(redisTemplate.opsForValue().get("system:sensitiveWord"));
        //SensitivewordFilter filter = new SensitivewordFilter(wordStr);
        //根据userId搜索user byUserId.get("name").toString(), byUserId.get("image").toString()
        Map<String, Object> byUserId = userFeign.findByUserId(Integer.valueOf(userId));
        //屏蔽词过滤为***
        if (StringUtils.isNotNull(text)) {
            //text = (filter.replaceSensitiveWord(text, 1, "*"));
            int i = baiduAipContentCensor.AipText(text);
            if (i == 2) {
                return AjaxResult.error("您发表言论不当,评论发表失败!");
            }
        }
        int i = sAnsweringCommentService.postComment(userId, byUserId.get("name").toString(), byUserId.get("image").toString(), resId, text, level);
        //答疑的老师id与发表评论userid进行对比
        if (i == 1) {
            //确定当前评论的内容是否是讨论还是老师发表的评论  1.resId 评论的父级id; 2.level 评论层级
            //1级评论针对老师的问题，2级评论针对一级评论
            if (level.equals("1")) {
                //针对老师的问题
                SAnswering sAnswering = answeringService.selectSAnsweringById(Integer.valueOf(resId));
                String teaUserId = String.valueOf(sAnswering.getUserId());
                //消息表-插入信息-业务逻辑---学生信息，讨论主题，评论内容，时间，针对的老师
                MessageNotification messageNotification = new MessageNotification();
                messageNotification.setDiscussTopic(sAnswering.getProblemTitle());
                messageNotification.setReplyContent(text);
                messageNotification.setTeaId(sAnswering.getUserId());
                //messageNotification.setTeaName(sAnswering.getTeacherName());
                messageNotification.setStuId(Integer.valueOf(userId));
                //messageNotification.setStuName(byUserId.get("name").toString());
                messageNotification.setCreatetime(new Date());
                messageNotification.setDiscussTopicId(sAnswering.getId());

                if (messageNotification.getTeaId().compareTo(messageNotification.getStuId()) != 0) {
                    messageNotificationService.insertMessageNotification(messageNotification);

                    Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
                    if (Objects.nonNull(res)) {
                        HomeData homeData = (HomeData) res;
                        homeData.setMessageWait(homeData.getMessageWait() + 1);
                        redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
                        WebSocketServerWELCO.sendInfo(homeData, teaUserId);
                    } else {
                        //数据初始化
                        Object data = homeBuffer.data(String.valueOf(teaUserId));
                        HomeData homeData = (HomeData) data;
                        homeData.setMessageWait(homeData.getMessageWait() + 1);
                        redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
                        WebSocketServerWELCO.sendInfo(homeData, teaUserId);
                    }
                }
                return AjaxResult.success("评论成功！");
            } else {
                //2级评论针对一级评论   得到resId的发布者
                SAnsweringComment sAnsweringComment = sAnsweringCommentService.selectCommentListByResId(Integer.valueOf(resId));//一级评论
                SAnswering sAnswering = answeringService.selectSAnsweringById(sAnsweringComment.getCPostId());
                Integer UserId = Integer.valueOf(sAnsweringComment.getCUserId());//一级评论的用户id
                //寻找老师表得到老师用户id集合
                List<TTeacher> tTeachersList = tTeacherService.selectTTeacherList(null);
                List<Integer> teaIdList = tTeachersList.parallelStream().map(tTeacher -> tTeacher.getUserId()).collect(Collectors.toList());
                if (!teaIdList.contains(UserId)) {
                    //消息表-插入信息-业务逻辑---学生信息，讨论主题，评论内容，时间，针对的老师

                    MessageNotification messageNotification = new MessageNotification();
                    messageNotification.setDiscussTopic(sAnsweringComment.getCPlText());
                    messageNotification.setReplyContent(text);
                    messageNotification.setTeaId(sAnswering.getUserId());
                    //messageNotification.setTeaName(sAnsweringComment.getCUserName());
                    messageNotification.setStuId(Integer.valueOf(userId));
                    //messageNotification.setStuName(byUserId.get("name").toString());
                    messageNotification.setCreatetime(new Date());
                    messageNotification.setDiscussTopicId(sAnswering.getId());

                    if (messageNotification.getTeaId().compareTo(messageNotification.getStuId()) != 0) {
                        messageNotificationService.insertMessageNotification(messageNotification);

                        String teaUserId = String.valueOf(UserId);
                        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
                        if (Objects.nonNull(res)) {
                            HomeData homeData = (HomeData) res;
                            homeData.setMessageWait(homeData.getMessageWait() + 1);
                            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
                            WebSocketServerWELCO.sendInfo(homeData, teaUserId);
                        } else {
                            //数据初始化
                            Object data = homeBuffer.data(String.valueOf(teaUserId));
                            HomeData homeData = (HomeData) data;
                            homeData.setMessageWait(homeData.getMessageWait() + 1);
                            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
                            WebSocketServerWELCO.sendInfo(homeData, teaUserId);
                        }
                        return AjaxResult.success("评论成功！");
                    }
                    return AjaxResult.success("评论成功！");
                }
                return AjaxResult.success("评论成功！");
            }
        }
        return AjaxResult.error("评论失败！");
    }

    /**
     * 点赞类型与举报类型
     *
     * @param likeId 点赞对象的id
     * @param userId 点赞用户的id
     * @param type   点赞对象的类型  评论-1
     * @return -1 未点赞    1 已点赞
     */
    @GetMapping("/commentLike")
    @ApiOperation(value = "答疑评论点赞", httpMethod = "GET")
    public AjaxResult commentLike(@RequestParam(value = "likeId", required = true) String likeId,
                                  @RequestParam(value = "userId", required = true) String userId,
                                  @RequestParam(value = "type", required = false) String type) {

        //根据userId搜索user
        Map<String, Object> byUserId = userFeign.findByUserId(Integer.valueOf(userId));
        //添加点赞记录    修改该资源的点赞数
        type = "5";
        return answeringLikeService.updateSysUserForumsLikeItData(userId, byUserId.get("name").toString(), byUserId.get("image").toString(), likeId, type);
    }

    /**
     * @param likeId 举报对象id
     * @param userId 举报人id
     * @param type   举报类型
     * @param text   举报文本
     * @return
     */
    @GetMapping("/commentReport")
    @ApiOperation(value = "答疑评论举报", httpMethod = "GET")
    public AjaxResult commentReport(@RequestParam(value = "likeId", required = true) String likeId,
                                    @RequestParam(value = "content", required = false) String content,
                                    @RequestParam(value = "userId", required = true) String userId,
                                    @RequestParam(value = "type", required = false) String type,
                                    @RequestParam(value = "text", required = true) String text) {

        //根据userId搜索user
        Map<String, Object> byUserId = userFeign.findByUserId(Integer.valueOf(userId));
        type = "5";//评论类型为5

        Map<String, Object> map = new HashMap<>();
        map.put("userID", userId);
        map.put("userName", byUserId.get("name").toString());
        map.put("userIco", byUserId.get("image").toString());
        map.put("cKeyId", likeId);
        //map.put("cKeyContent", content);
        map.put("cReportType", type);
        map.put("cReportRsn", text);
        reportService.insertSysForumsReport(map);
        return AjaxResult.success("举报成功！");
    }

    /**
     * 查所有二级目录下的答疑列表  首先得到二级目录列表   根据二级目录id去查找（in）  关联答疑表
     *
     * @param lessonId 课程id   最高级别
     * @param classId  班级id
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "查所有二级目录下的答疑列表", httpMethod = "GET")
    public AjaxResult sAnsweringList(@RequestParam(value = "lessonId", required = true) Integer lessonId,
                                     @RequestParam(value = "classId", required = false) Integer classId) {

        //获取二级目录集合
        List<SCatalogMenu> TwoCataList = selectTwoList(lessonId);
        //流转换对象
        List<Integer> twoIntList = TwoCataList.stream().map(a -> a.getId()).collect(Collectors.toList());
        //查找所有二级目录下的答疑资源
        SAnswering sAnswering = new SAnswering();
        //sAnswering.setIsStu("1");
        //sAnswering.setClassId(classId);
        sAnswering.setTwoIDList(twoIntList);
        List<SAnswering> sAnsweringList = answeringService.selectSAnsweringStuList(sAnswering);
        return AjaxResult.success(sAnsweringList);
    }

    public List<SCatalogMenu> selectTwoList(Integer lessonId) {
        SCatalogMenu sCatalogMenu = new SCatalogMenu();
        //查询出第0级列表
        sCatalogMenu.setParentId(0);
        sCatalogMenu.setId(lessonId);
        //第0级
        SCatalogMenu list = catalogMenuService.selectSCatalogMenuList2(sCatalogMenu);
        //一级 以及 下面子列表
        return listSon2(list);
    }

    //查询目录列表
    public List<SCatalogMenu> listSon2(SCatalogMenu cList) {
        //根据课程id查询出一级目录列表jrCatalogs
        List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(cList.getId());
        if (jrCatalogs != null && jrCatalogs.size() > 0) {
            //设置子级集合
            //cList.setChildren(listSon(jrCatalogs));
            return listSon(jrCatalogs);
        }
        return null;
    }

    public List<SCatalogMenu> listSon(List<SCatalogMenu> cList) {
        List<SCatalogMenu> twoSCatalogMenu = new ArrayList<>();
        for (SCatalogMenu catalogMenu : cList) {
            //根据第一级的id查询出二级列表
            List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(catalogMenu.getId());
            //二级列表汇总
            twoSCatalogMenu.addAll(jrCatalogs);
            if (jrCatalogs != null && jrCatalogs.size() > 0) {
                //设置子级集合
                //catalogMenu.setChildren(listSon(jrCatalogs));
                //catalogMenu.setChildren(jrCatalogs);
            }
        }
        return twoSCatalogMenu;
    }

    @ApiOperation(value = "学校课程--答疑接口", httpMethod = "GET")
    @GetMapping("/selectByAnswering")
    public ApiReturnObject selectByAnswering(Integer catalogId, Integer userId, Integer answerId) {
        if (null != catalogId) {
            //调用服务查找班级id
            Map<String, Object> clIdMap = userFeign.findByUserId(userId);
            Integer classId = Integer.parseInt(clIdMap.get("classId").toString());
            //准备答疑对象
            SAnswering sAnswering = new SAnswering();
            sAnswering.setCatalogId(catalogId);
            sAnswering.setId(answerId);
            sAnswering.setIsStu("1");//是否允许学生查看
            sAnswering.setClassId(classId);
            //调用service 查找老师分享给班级的答疑列表
            List<SAnswering> sAnsweringList = answeringService.selectSAnsweringList(sAnswering);

            for (SAnswering answering : sAnsweringList) {
                //获取答疑用户(老师)的头像和名称
                Map<String, Object> map = userFeign.findByUserId(answering.getUserId());
                answering.setName(map.get("name").toString());
                answering.setImage(map.get("image").toString());
                //当前答疑来自于课程名称
                SCatalog catalog = new SCatalog();
                catalog.setParentId(catalogId);
                List<SCatalog> catalogList = isCatalogService.selectSCatalogList(catalog);
                if (catalogList.size() != 0) {
                    answering.setCatalogName("来自" + catalogList.get(0).getCatalogName() + "课程的知识");
                    answering.setTeacherId(answering.getUserId());//老师id
                }
                //查询当前学生用户是否点赞
                if (userId != null) {
                    SAnswerUser sAnswerUser = new SAnswerUser();
                    sAnswerUser.setUserId(userId);
                    sAnswerUser.setAnswerId(answering.getId());
                    List<SAnswerUser> sAnswerUsers = isAnswerUserService.selectSAnswerUserList(sAnswerUser);
                    if (sAnswerUsers.size() == 0) {
                        // 0 未点赞  1  已点赞
                        answering.setIsLike("0");
                    } else {
                        // 0 未点赞  1  已点赞
                        answering.setIsLike("1");
                    }
                }
            }

            return new ApiReturnObject("200", "查询成功", sAnsweringList.size(), sAnsweringList);
        } else {
            return new ApiReturnObject("201", "参数缺失", "参数缺失");
        }
    }

    @ApiOperation(value = "学校课程--点赞接口", httpMethod = "POST")
    @PostMapping("/fabulous")
    public ApiReturnObject fabulous(Integer answerId, Integer userId) {
        if (null == answerId || null == userId) {
            return new ApiReturnObject("201", "answerId或userId为空", "answerId或userId为空");
        } else {
            //根据userid和answerid查询主键表是否有数据 有 : 取消点赞  没有 : 点赞
            SAnswerUser sAnswerUser = new SAnswerUser();
            sAnswerUser.setAnswerId(answerId);
            sAnswerUser.setUserId(userId);
            List<SAnswerUser> answerUserList = isAnswerUserService.selectSAnswerUserList(sAnswerUser);
            if (answerUserList.size() == 0) {
                //添加点赞记录到中间表
                SAnswerUser answerUser = new SAnswerUser();
                answerUser.setAnswerId(answerId);
                answerUser.setUserId(userId);
                answerUser.setCreateTime(new Date());
                isAnswerUserService.insertSAnswerUser(answerUser);

                //修改点赞数   +1
                SAnswering sAnswering = answeringService.selectSAnsweringById(answerId);
                SAnswering answer = new SAnswering();
                answer.setId(sAnswering.getId());
                if (null == sAnswering.getFabulous()) {
                    answer.setFabulous(1);
                } else {
                    answer.setFabulous(sAnswering.getFabulous() + 1);
                }
                answeringService.updateSAnswering(answer);
                SAnswering answ = answeringService.selectSAnsweringById(answerId);
                //是否点赞  0 未点赞  1  已点赞
                answ.setIsLike("1");
                return new ApiReturnObject("200", "点赞成功", answ);
            } else {
                //删除中间表该点赞记录
                SAnswerUser answerUser = new SAnswerUser();
                answerUser.setAnswerId(answerId);
                answerUser.setUserId(userId);
                isAnswerUserService.deleteSAnswerUserByUserIdAndAnswerId(answerUser);

                //修改点赞数   -1
                SAnswering sAnswering = answeringService.selectSAnsweringById(answerId);
                SAnswering answer = new SAnswering();
                answer.setId(sAnswering.getId());
                if (null == sAnswering.getFabulous()) {
                    answer.setFabulous(0);
                } else {
                    if (sAnswering.getFabulous() > 0) {
                        answer.setFabulous(sAnswering.getFabulous() - 1);
                    } else {
                        return new ApiReturnObject("203", "点赞数不能为负数", "点赞数不能为负数");
                    }
                }
                answeringService.updateSAnswering(answer);
                SAnswering answ = answeringService.selectSAnsweringById(answerId);
                //是否点赞  0 未点赞  1  已点赞
                answ.setIsLike("0");
                return new ApiReturnObject("200", "取消点赞成功", answ);
            }
        }
    }


   /* @ApiOperation(value = "学校课程--点赞接口", httpMethod = "POST")
    @PostMapping("/fabulous")
    public ApiReturnObject fabulous1(Integer answerId, Integer type) {
        if (null == answerId || null == type) {
            return new ApiReturnObject("201", "catalogId或type为空", "catalogId或type为空");
        } else {
            SAnswering sAnswering = answeringService.selectSAnsweringById(answerId);
            // 0 点赞  1  取消点赞
            if (type == 0) {
                SAnswering answer = new SAnswering();
                answer.setId(sAnswering.getId());
                if (null == sAnswering.getFabulous()) {
                    answer.setFabulous(1);
                } else {
                    answer.setFabulous(sAnswering.getFabulous() + 1);
                }
                answeringService.updateSAnswering(answer);
                return new ApiReturnObject("200", "点赞成功", "点赞成功");
            } else if (type == 1) {
                SAnswering answer = new SAnswering();
                answer.setId(sAnswering.getId());
                if (null == sAnswering.getFabulous()) {
                    answer.setFabulous(1);
                } else {
                    if (sAnswering.getFabulous() > 0) {
                        answer.setFabulous(sAnswering.getFabulous() - 1);
                    } else {
                        return new ApiReturnObject("203", "点赞数不能为负数", "点赞数不能为负数");
                    }
                }
                answeringService.updateSAnswering(answer);
                return new ApiReturnObject("200", "取消点赞成功", "取消点赞成功");
            } else {
                return new ApiReturnObject("202", "type参数值有误 请输入0 :点赞 或 1 : 取消点赞", "type参数值有误 请输入0 :点赞 或 1 : 取消点赞");
            }
        }
    }
*/

}